var reading = $("#reading");
var otherQuestions = $("#otherQuestions");
var save = $("#save");
var addItem = $("#addItem");
var topicSort = $("#topicSort");
var TitleDetailAll = $("#TitleDetailAll");
var topicReadingId = sessionStorage.getItem("topicReadingId");
sessionStorage.removeItem("topicReadingId");
var topicDetailName=sessionStorage.getItem("topicDetailName");
var topicReadingIdData = {
    "topicId": topicReadingId,
    "token": User.token
};
topicReadingIdData = JSON.stringify(topicReadingIdData);
updateObject(Doman.url + Doman.topicIdGet, true, topicReadingIdData, function (data) {
    reading.find(".readingContent").html(data.topicDetail.topicGetData.content);
    reading.attr("parentId", data.topicDetail.topicId);
    if (data.topicDetail.sonWordList.length != 0) {
        readingList(data.topicDetail);
    }
}, function () {
});

/**题目详情页展示收缩**/
$(document).on('click', ".TitleDetail_title", function () {
    $(this).next().toggle();
});


//点击添加小题
addItem.on("click", function () {
    save.find("button").addClass("saveReading");
    otherQuestions.css("display", "block");
    save.css("display", "block");
    topicSort.css("display", "none");//排序隐藏
    $(document).scrollTop($(".container")[0].offsetHeight);
    $("#myModal .modal-header h4").html("请添加内容");
});

//点击保存小题及其排序
save.on("click", ".saveReading", function () {
    //将ueditor img src64 转换为_src中文件中的上传到地址服务器的地址
    $.each($("#myEditor img"), function (i, data) {
        data.setAttribute("src", data.getAttribute("_src"));
    });
    var type = $("#questionType .select input").attr("data-value");
    var parentId = reading.attr("parentId");
    if (($("#questionType .select input").attr("data-value") == "1") && ($("#radioSelect")[0].checked || $("#multiSelect")[0].checked)) {
        var optionNum = $("#selection .optionsNum input").val();
        var answers = [];
        $.each($("#selection .answer .options input"), function (i, data) {
            if (data.checked) {
                if (data.id == "yes") {
                    answers.push("Y");
                } else if (data.id == "no") {
                    answers.push("N");
                } else {
                    answers.push(data.id);
                }
            }
        });
    }
    if (($("#questionType .select input").attr("data-value") == "1") && ($("#judgSelect")[0].checked)) {
        var verdict = $("#selection .answer .options input:checked").val();
    }
    if ($("#questionType .select input").attr("data-value") == "3") {
        var inputMode = $("#subjectFill .options input:checked").val()
    }
    if ($("#upload .mp3 input:last-child").val()) {
        var hearingFile = $("#upload .mp3 input:last-child").val();
    }
    if ($("#upload .jpg input:last-child").val()) {
        var answerFile = $("#upload .jpg input:last-child").val();
    }
    var content = UM.getEditor('myEditor').getContent();
    var dataValue = $(".select input").attr("data-value");
    if (content == "") {
        if (dataValue == 1) {
            if (!$(".answer").find(".on").length && !$(".answer").find(".on_check").length) {
                $(".selectError").css("display", "inline-block");
            } else {
                $(".selectError").css("display", "none");
            }
        } else if (dataValue == 3) {
            if (!$("#subjectFill .options").find(".on").length) {
                $(".selectError").css("display", "inline-block");
            } else {
                $(".selectError").css("display", "none");
            }
        }
        $("#modelClick").trigger('click');
    } else {
        if (dataValue == 1) {
            if (!$(".answer").find(".on").length && !$(".answer").find(".on_check").length) {
                $(".selectError").css("display", "inline-block");
            } else {
                $(".selectError").css("display", "none");
                if (sessionStorage.getItem("topicIdUpdate") == null) {
                    sontopicSave(parentId, type, optionNum, answers, verdict, inputMode, answerFile, hearingFile, content, sontopicList);
                } else {
                    var topicId = sessionStorage.getItem("topicIdUpdate");
                    topicIdUpdate(type, optionNum, answers, verdict, inputMode, answerFile, hearingFile, content, topicId);
                    sessionStorage.removeItem("topicIdUpdate")
                }
            }
        } else if (dataValue == 3) {
            if (!$("#subjectFill .options").find(".on").length) {
                $(".selectError").css("display", "inline-block");
            } else {
                $(".selectError").css("display", "none");
                if (sessionStorage.getItem("topicIdUpdate") == null) {
                    sontopicSave(parentId, type, optionNum, answers, verdict, inputMode, answerFile, hearingFile, content, sontopicList);
                } else {
                    var topicId = sessionStorage.getItem("topicIdUpdate");
                    topicIdUpdate(type, optionNum, answers, verdict, inputMode, answerFile, hearingFile, content, topicId);
                    sessionStorage.removeItem("topicIdUpdate")
                }
            }
        } else {
            if (sessionStorage.getItem("topicIdUpdate") == null) {
                sontopicSave(parentId, type, optionNum, answers, verdict, inputMode, answerFile, hearingFile, content, sontopicList);
            } else {
                var topicId = sessionStorage.getItem("topicIdUpdate");
                topicIdUpdate(type, optionNum, answers, verdict, inputMode, answerFile, hearingFile, content, topicId);
                sessionStorage.removeItem("topicIdUpdate")
            }
        }
    }
});

/**
 * 阅读题小题保存
 * **/
function sontopicSave(parentId, type, optionNum, answers, verdict, inputMode, answerFile, hearingFile, content, callback) {
    var sontopicSave = {
        "parentId": parentId,
        "type": type,
        "optionNum": optionNum == undefined ? "" : optionNum,
        "answers": answers,
        "verdict": verdict == undefined ? "" : verdict,
        "inputMode": inputMode == undefined ? "" : inputMode,
        "answerFile": answerFile == undefined ? "" : answerFile,
        "hearingFile": hearingFile == undefined ? "" : hearingFile,
        "content": content,
        "token": User.token,
        "timeStamp": 11111,
        "os": "qqq",
        "version": "1",
        "session": "1",
        "signature": "1"
    };
    sontopicSave = JSON.stringify(sontopicSave);
    console.log(sontopicSave)
    $.ajax({
        type: 'POST',  //POST/PUT/DELETE/HEAD
        url: Doman.url + Doman.sontopicSave,
        contentType: "application/json",
        data: sontopicSave,
        success: function (data) {
            save.css("display", "none");
            callback(data);
        },	//成功响应的回调
        error: function () {
            console.log("error");
        }		//失败响应的回调
    });
}
function sontopicList(data) {
    sessionStorage.setItem('topicReadingId', topicReadingId);
    openUrl(window.location.href,"TopicManageDetail.html",topicDetailName);
    openUrl(window.location.href,"AddReadingTopic.html","添加小题");
}

/**
 * 阅读题内部小题列表
 * **/
function readingList(data) {
    var sonWordList = data.sonWordList;
    if(sonWordList.length>1){
        topicSort.css("display", "block");
    }
    var html = "<ul id='readingListSort'>";
    sonWordList.forEach(function (sonWord, index) {
        html +=
           '<li topicid='+sonWord.topicId+'>'+
                '<div class="TitleDetail">'+
                    '<div class="TitleDetail_title">'+
                        '<span class="TitleNo"><span>'+(index + 1)+'</span></span>'+
                        '<span class="TitleType">'+sonWord.type+'</span>'+
                        '<a href="#" class="TitleModify">&nbsp;</a>'+
                        '<a href="#" data-toggle="modal" data-target="#myModal" class="btn btn-danger topicRevocation">删除</a>'+
                    '</div>'+
                    '<div class="TitleDetail_content">'+
                        '<div class="question">'+ sonWord.content+
                        '</div>'+
                        '<div class="answer">' + ((sonWord.answers == "" || sonWord.answers == undefined ) ? " " : ('答案: <span>'+sonWord.answers+'</span></div>'))+((sonWord.hearingFile == "") ? "" : ('<div class="video">'+
                        '<a href='+sonWord.hearingFile+'class="video_img"></a>'+
                        '<span>'+sonWord.fileLength+'"</span>'+
                    '</div>'))+
                    '<div class="detail"></div>'+
                    '</div>'+
                '</div>'+
            '</li>';
    });
    html+="</ul>";
    TitleDetailAll.html(html);
    for (var i = 0; i < sonWordList.length; i++) {
        var titleType = $(".TitleType")[i];
        switch (parseInt(titleType.innerHTML)) {
            case 1:
                titleType.innerHTML = "选择题";
                break;
            case 2:
                titleType.innerHTML = "客观填空";
                break;
            case 3:
                titleType.innerHTML = "主观填空";
                break;
            case 4:
                titleType.innerHTML = "简答题";
                break;
            case 5:
                titleType.innerHTML = "阅读题";
                break;
            case 6:
                titleType.innerHTML = "口语训练题";
                break;
            case 7:
                titleType.innerHTML = "解答题";
                break;
            case 8:
                titleType.innerHTML = "选择性填空题";
                break;
            case 9:
                titleType.innerHTML = "判断题";
                break;
            case 10:
                titleType.innerHTML = "多选题";
                break;
            case 11:
                titleType.innerHTML = "听力题";
                break;
            case 12:
                titleType.innerHTML = "英语口语训练";
                break;
            case 13:
                titleType.innerHTML = "语文口语训练";
                break;
            default :
                break;
        }
    }
    contentModify();
}

/**
 * 对答案进行处理 分为详解和内部答案
 * **/
function contentModify() {
    $(".question").each(function (i) {
        var content = $(this).html();
        content = content.replace(/\[答案始]/g, "<span class='answerModify'>");
        content = content.replace(/\[\/答案终]/g, "</span>");
        var arr = content.match(/\[详解始](.*?)\[\/详解终]/g);
        var detailSelector = $(this).parent().find(".detail");
        if (arr != null) {
            var html = "详解：";
            $.each(arr, function (i, n) {
                arr[i] = String(arr[i]).replace(/\[详解始]/g, "");
                arr[i] = String(arr[i]).replace(/\[\/详解终]/g, "");
                html += "<p>" + arr[i] + "</p>";
                detailSelector[0].innerHTML = html;
            });
        }
        content = content.replace(/\[详解始](.*?)\[\/详解终]/g, "");
        $(this).html(content);
    });
}

/**
 * 点击删除小题
 * **/
$(document).on("click", ".topicRevocation", function (event) {
    event.stopPropagation();
    $("#myModal .modal-header h4").html("是否删除");
    var sonWorkId = parseInt($(this).parent().parent().parent().attr("topicid"));
    var parentId = reading.attr("parentId");
    var sontopicRevocation = {
        "sonWorkId": sonWorkId,
        "parentId": parentId
    };
    sontopicRevocation = JSON.stringify(sontopicRevocation);
    $("#myModal .reconfirm").on("click", function () {
        console.log(sontopicRevocation)
        $.ajax({
            type: 'POST',  //POST/PUT/DELETE/HEAD
            url: Doman.url + Doman.sontopicRevocation,
            contentType: "application/json",
            data: sontopicRevocation,
            success: function (data) {
                sessionStorage.setItem('topicReadingId', topicReadingId);
                openUrl(window.location.href,"TopicManageDetail.html",topicDetailName);
                openUrl(window.location.href,"AddReadingTopic.html","添加小题");
            },	//成功响应的回调
            error: function () {
                console.log("error");
            }		//失败响应的回调
        });
    });
});

/**
 * 点击修改触发事件
 * **/
$(document).on('click', ".TitleModify", function (event) {
    event.stopPropagation();
    var topicId = $(this).parent().parent().parent().attr("topicid");
    var topicDetailNameModify = sessionStorage.getItem("topicDetailName")
    openUrl(window.location.href, "AddTopic.html", "修改题目");
    sessionStorage.setItem('topicId', topicId);
    sessionStorage.setItem('topicDetailNameModify', topicDetailNameModify);
    sessionStorage.setItem('topicReadingId', topicReadingId);
});

/**题目详情页排序可拖拽**/
$("#topicSort")[0].onclick = function () {
    $(" .TitleDetail_content").css("display", "none");
    $(this).next().css("display", "inline-block");
    $(this).next().next().css("display", "inline-block");
    $(this).css("display", "none");
    $(this).prev().css("display", "none");
    //$("#TopicManageDetail_popup .popup_title span").css("display", "none");
    window.x = new Sortable(readingListSort, {
        group: "words",
        store: {
            get: function (sortable) {
                var order = localStorage.getItem(sortable.options.group);
                return order ? order.split('|') : [];
            },
            set: function (sortable) {
                var order = sortable.toArray();
                order = [];
                localStorage.setItem(sortable.options.group, order.join('|'));
            }
        },
        onEnd: function () {
            var spanArr = $("#TitleDetailAll .TitleDetail .TitleNo span");
            for (var i = 0; i < spanArr.length; i++) {
                spanArr[i].innerHTML = i + 1;
            }
        }
    });
};

/**题目详情页排序可保存**/
$("#topicSortSave")[0].onclick = function () {
    $(this).css("display", "none");
    $(this).next().css("display", "none");
    $(this).prev().css("display", "inline-block");
    $(this).prev().prev().css("display", "inline-block");
    //$("#TopicManageDetail_popup .popup_title span").css("display", "inline-block");
    $(" .TitleDetail_content").css("display", "block");
    topicIdListSort();
};

/**保存排序**/
function topicIdListSort(){
    var topicIdList = [];
    for (var i = 0; i < $("#readingListSort li").length; i++) {
        topicIdList.push(parseInt($("#readingListSort li")[i].getAttribute("topicid")));
    }
    var topicGroupId = parseInt($("#TitleDetailAll").attr("groupid"));
    var sontopicSort = {
        "topicIdList": topicIdList,
        "groupid": "0",
        //"session": "f62d02686659112a0246f059fd9d4581",
        "timeStamp": User.timeStamp,
        "token": User.token
    };
    sontopicSort = JSON.stringify(sontopicSort);
    $.ajax({
        type: 'POST',  //POST/PUT/DELETE/HEAD
        url: Doman.url + Doman.sontopicSort,
        contentType: "application/json",
        data: sontopicSort,
        success: function (data) {
            sessionStorage.setItem('topicReadingId', topicReadingId);
            openUrl(window.location.href,"TopicManageDetail.html",topicDetailName);
            openUrl(window.location.href,"AddReadingTopic.html","添加小题");
        },	//成功响应的回调
        error: function () {
            console.log("error");
        }		//失败响应的回调
    });
};

/**点击取消排序 确认保存**/
$("#TopicManageDetailCancel .reconfirm").on("click",function(){
    $(this).css("display", "none");
    $(this).next().css("display", "none");
    $(this).prev().css("display", "inline-block");
    $(this).prev().prev().css("display", "inline-block");
    //$("#TopicManageDetail_popup .popup_title span").css("display", "inline-block");
    $(" .TitleDetail_content").css("display", "block");
    topicIdListSort();
});
/**点击取消排序 确认保存**/
$("#TopicManageDetailCancel .cancel").on("click",function(){
    sessionStorage.setItem('topicReadingId', topicReadingId);
    openUrl(window.location.href,"TopicManageDetail.html",topicDetailName);
    openUrl(window.location.href,"AddReadingTopic.html","添加小题");
});